package com.ligongmusic.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ligongmusic.R;
import com.ligongmusic.util.ActivityManager;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StorageUtils;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.MyToast;

@SuppressWarnings("deprecation")
public class UserLogin extends Activity {
    private MyToast toast;
    private EditText et_pwd;
    private EditText et_name;
    private boolean isClick = false;
    String username;
    String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
        save(et_name.getText().toString(),et_pwd.getText().toString());
        getToken();
        login(username,password);
    }

    /*存储用户名密码，以及返回的参数*/
    private void save(final String userName, final String passWord){
        SharedPreferences sharedPreferences=getSharedPreferences("login",0);
        sharedPreferences.edit().putString("loginname",userName).commit();
        sharedPreferences.edit().putString("loginpass",passWord).commit();
    }

    /*获取用户名密码，token*/
    public void  getToken(){
        SharedPreferences sharedPreferences=getSharedPreferences("login",0);
        username=sharedPreferences.getString("loginname","");
        password=sharedPreferences.getString("loginpass","");
    }

    private void initView() {
        toast = new MyToast(this);
        et_name = (EditText) findViewById(R.id.et_user_name);
        et_pwd = (EditText) findViewById(R.id.et_pass_word);
        // 读取首选项中保存的用户名及密码
        String userName = StorageUtils.getInstance(getApplicationContext()).getValue(GlobalParams.userNameKey);
        if (!StringUtils.isEmpty(userName)) {
            et_name.setText(userName);
            String pwd = StorageUtils.getInstance(getApplicationContext()).getValue(userName);
            if (!StringUtils.isEmpty(pwd))
                et_pwd.setText(pwd);
            else
                et_pwd.setText("");
        }
        // 注册
        ((TextView) findViewById(R.id.tv_register)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.startActivity(UserLogin.this, UserRegister.class);
            }
        });
        // 忘记密码
        ((TextView) findViewById(R.id.tv_forget_pwd)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.startActivity(UserLogin.this, ForgetPassWord.class);
            }
        });
        //登录
        ((Button) findViewById(R.id.bt_login)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isClick)
                    return;
                String userName = et_name.getText().toString().trim();
                if (StringUtils.isEmpty(userName)) {
//                    Toast.makeText(getApplicationContext(), "用户名不能为空", Toast.LENGTH_SHORT).show();
                    toast.toastShow("用户名不能为空");
                    return;
                }
                String passWord = et_pwd.getText().toString().trim();
                if (StringUtils.isEmpty(passWord)) {
                    toast.toastShow("密码不能为空");
//                    Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passWord.length() < 6 || passWord.length() > 12) {
                    toast.toastShow("密码长度为6-12位");
//                    Toast.makeText(getApplicationContext(), "密码长度为6-12位", Toast.LENGTH_SHORT).show();
                    return;
                }
                isClick = true;
                login(userName, passWord);
            }
        });
    }

    private void login(final String userName, final String passWord) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("loginname", userName));
        pairs.add(new BasicNameValuePair("loginpass", passWord));
        NetWorkUtils.postRequest(pairs, GlobalParams.LOGIN, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                isClick = false;
                Log.e("LoggerUtils", "success: " + result);
                if (result == null) {
                    toast.toastShow("登录失败，请重试");
//                    Toast.makeText(getApplicationContext(), "登录失败，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    String code = JsonUtils.getString(result, "code");
                    toast.toastShow(JsonUtils.getString(result, "message"));
//                    Toast.makeText(getApplicationContext(), JsonUtils.getString(result, "message"), Toast.LENGTH_SHORT).show();
                    if ("200".equals(code)) {
                        // 成功 TODO
                        GlobalParams.token = JsonUtils.getString(result, "object");
                        GlobalParams.userName = userName;
                        // 保存首选项
                        // 如果用户选中记住密码，则保存密码(使用用户名作为取密码的key，防止同客户端多用户登录时取错密码)
                        StorageUtils.getInstance(UserLogin.this).writeString(GlobalParams.userNameKey, userName);
                        StorageUtils.getInstance(UserLogin.this).writeString(userName, passWord);
                        // 跳转主界面
//						ActivityManager.startActivity(UserLogin.this, MainActivity.class);
                        GlobalParams.isLogin = true;
                        // TODO 改权限
                        GlobalParams.userStatus = (1 == JsonUtils.getInt(result, "status"));
                        setResult(0x7);
                        finish();
                    }
                } catch (Exception e) {
                    toast.toastShow("登录失败，请重试");
//                    Toast.makeText(getApplicationContext(), "登录失败，请重试", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void error(String message) {
                isClick = false;
                toast.toastShow("登录失败，请重试");
//                Toast.makeText(getApplicationContext(), "登录失败，请重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void error() {
                isClick = false;
                toast.toastShow("登录失败，请重试");
//                Toast.makeText(getApplicationContext(), "登录失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(0x8);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
